import axios from 'axios'
import _ from 'lodash';
import {
  randomWord, getSign
} from './tools'
import router from '@/router'
import store from '@/store'
import mTypes from '@/store/mutationsTypes'
import {message} from 'ant-design-vue'
const appid = '40bd001563085fc35165329ea1ff5c5ecbdbbeef'
const app_secret = '3f666c39681952deec3d2e2e673ad78450fa8af810653852fb7f18eb240c521c'
const baseURL = 'https://newyxp.sse100.com/'
// const baseURL = 'https://e-school.yixuepai100.com/'
// const indexURL = 'https://e-school.yixuepai100.com'
const indexURL = 'https://newyxp.sse100.com'
const prefix = 'api'
const requestList = []
// 取消列表
const CancelToken = axios.CancelToken
let sources = {}
axios.defaults.timeout = 5000
axios.defaults.withCredentials = false
axios.defaults.headers['Content-Type'] = 'application/json;charset=UTF-8'
axios.defaults.headers['appid'] = appid
axios.defaults.baseURL = `${baseURL}${prefix}`
function pruneEmpty(obj) {
  return function prune(current) {
    _.forOwn(current, function (value, key) {
      if(value === 0){
        current[key] = '0'
        value = '0'
      }
      if ((_.isUndefined(value) || _.isNull(value) || _.isNaN(value) ||
        (_.isString(value) && _.isEmpty(value)) ||
        (_.isObject(value) && _.isEmpty(prune(value)))) && value !== 0) {
        delete current[key];
      }
    });
    // remove any leftover undefined values from the delete
    // operation on an array
    if (_.isArray(current)) _.pull(current, undefined);
    return current;

  }(_.cloneDeep(obj)); // Do not modify the original object, create a clone instead
}


axios.interceptors.request.use((config) => {
  let timestamp = new Date().valueOf(),
  noncestr = randomWord(true, 16, 32)
  console.log(config.data)
  if (config.url === '/usercenter/courseinfo') {} else if (config.url === '/usercenter/courseindex' && config.data.has_course === '0') {} else {
    let {access_token} = JSON.parse(window.localStorage.getItem('vuexStorage'))
    if (access_token) {
      config.data = Object.assign({}, config.data, {access_token})
    }
  }
  let sign = getSign(config.data, {appid, appsecret: app_secret, noncestr, timestamp })
  config.url = `${config.url}?sign=${sign}`
  config.headers['timestamp'] = timestamp
  config.headers['noncestr'] = noncestr
  const request = JSON.stringify(config.url) + JSON.stringify(config.data)
  config.cancelToken = new CancelToken((cancel) => {
    sources[request] = cancel
  })
  if (requestList.includes(request)) {
    sources[request]('取消重复请求')
  } else {
    requestList.push(request)
  }
  return config
}, function (error) {
  console.log(error, 'error', 'request')
  return Promise.reject(error)
})

axios.interceptors.response.use(function (response) {
  const request = JSON.stringify(response.config.url) + JSON.stringify(response.config.data)
  requestList.splice(requestList.findIndex(item => item === request), 1)
  if (requestList.length === 0) {
    // 整体请求完成
  }
  // if (_.get(response, 'data', '') && _.get(response, 'data.code', '')) {
  //   let errorCode = response.data.code
  // }
  return response
}, function (error) {
  if (_.get(error, 'response.data', '') && _.get(error, 'response.data.code', '')) {
    // let errorCode = +error.response.data.code
    // switch (errorCode) {
    // }
  }

  if (error.response && error.response.data && error.response.data.msg) {
    message.error(error.response.data.msg)
  }
  requestList.length = 0
  if (axios.isCancel(error)) {
    requestList.length = 0
    console.log('取消请求')
    // throw new axios.Cancel('cancel request')
  } else {
    // 请求失败
    // const request = JSON.stringify(error.config.url) + JSON.stringify(error.config.data)
    // requestList.splice(requestList.findIndex(item => item === request), 1)
  }
  return Promise.reject(error)
})

const request = function (method, {
  url,
  params,
  data,
  headers,
  config
}) {
  return new Promise((resolve, reject) => {
    let resultData = pruneEmpty(data)
    let resultParams = pruneEmpty(params)
    axios({
      method: method.toLowerCase(),
      ...config,
      params: resultParams,
      url,
      data: resultData
    }).then(response => {
      let code = _.get(response, 'data.code', '')
      let info = _.get(response, 'data.info', '')
      if (code === 1) {
        let access_token = _.get(response.data, 'data.access_token', '')
        if (access_token) {
          store.commit(mTypes.setLoginInfo, access_token)
        }
      } else {
        if ([10001].includes(code)) {
          store.commit(mTypes.setLoginInfo, '')
          store.commit(mTypes.userInfo, '')
          router.push('/')
        }
        message.error(info)
      }
      resolve(response.data)
    }, err => {
      if (err.Cancel) {
        console.log(err)
      } else {
        reject(err)
      }
    }).catch(err => {
      reject(err)
    })
  })
}
const http = {
  get(paramBean) {
    let {
      data
    } = paramBean
    paramBean.params = data
    return request('get', paramBean)
  },
  post(paramBean) {
    return request('post', paramBean)
  },
  put(paramBean) {
    return request('put', paramBean)
  },
  delete(paramBean) {
    return request('delete', paramBean)
  }
}
export {
  sources,
  http,
  indexURL
}
